import { FastifyInstance, FastifyError } from 'fastify';
import { ZodError } from 'zod';
import { ApiResponseBuilder, ErrorCode } from '../types/index.js';

/**
 * 全局错误处理中间件
 */
export async function errorHandler(fastify: FastifyInstance) {
  // 设置错误处理器
  fastify.setErrorHandler(async (error: FastifyError, request, reply) => {
    const { log } = request;
    
    // 记录错误信息
    log.error({
      error: {
        message: error.message,
        stack: error.stack,
        statusCode: error.statusCode,
        validation: error.validation
      },
      request: {
        method: request.method,
        url: request.url,
        headers: request.headers,
        ip: request.ip
      }
    }, '请求处理出错');

    // 处理不同类型的错误
    if (error instanceof ZodError) {
      // Zod 验证错误
      const validationErrors = (error).issues.map((err: any) => ({
        field: err.path.join('.'),
        message: err.message,
        code: err.code
      }));

      const response = ApiResponseBuilder.error(
        ErrorCode.VALIDATION_ERROR,
        '请求参数验证失败',
        { validationErrors },
        { requestId: request.id }
      );

      return reply.status(400).send(response);
    }

    // Fastify 内置错误处理
    if (error.statusCode) {
      let errorCode: ErrorCode;
      let message: string;

      switch (error.statusCode) {
        case 400:
          errorCode = ErrorCode.VALIDATION_ERROR;
          message = '请求参数无效';
          break;
        case 401:
          errorCode = ErrorCode.UNAUTHORIZED;
          message = '未授权访问';
          break;
        case 403:
          errorCode = ErrorCode.FORBIDDEN;
          message = '禁止访问';
          break;
        case 404:
          errorCode = ErrorCode.NOT_FOUND;
          message = '资源未找到';
          break;
        case 429:
          errorCode = ErrorCode.RATE_LIMIT_EXCEEDED;
          message = '请求频率超限';
          break;
        default:
          errorCode = ErrorCode.INTERNAL_ERROR;
          message = error.message || '内部服务器错误';
      }

      const response = ApiResponseBuilder.error(
        errorCode,
        message,
        { originalError: error.message },
        { requestId: request.id }
      );

      return reply.status(error.statusCode).send(response);
    }

    // 未知错误
    const response = ApiResponseBuilder.error(
      ErrorCode.INTERNAL_ERROR,
      '内部服务器错误',
      process.env['NODE_ENV'] === 'development' ? { 
        stack: error.stack,
        originalMessage: error.message 
      } : undefined,
      { requestId: request.id }
    );

    return reply.status(500).send(response);
  });

  // 404 处理器
  fastify.setNotFoundHandler(async (request, reply) => {
    const response = ApiResponseBuilder.error(
      ErrorCode.NOT_FOUND,
      `路由 ${request.method} ${request.url} 未找到`,
      undefined,
      { requestId: request.id }
    );

    return reply.status(404).send(response);
  });
}
